package com.lucifer.cloud.boot.blog.nl2sql.engine;

import com.lucifer.cloud.boot.blog.nl2sql.service.IExecuteSqlService;
import com.lucifer.cloud.boot.blog.nl2sql.vector.BaseVectorStore;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @author lucifer
 * @date 2025/3/14 14:46
 */
@Slf4j
@Component
public class SpringSqlEngine extends AbstractSqlEngine{

    @Resource
    private  IExecuteSqlService executeService;


    public SpringSqlEngine setChatModel(ChatModel chatModel){
        super.chatModel= chatModel;
        return this;
    }

    @Override
    public SpringSqlEngine builder(BaseVectorStore vectorStore, RagEngine ragEngine, ChatModel chatModel, ResourceLoader resourceLoader) {
        super.vectorStore = vectorStore;
        super.ragEngine =ragEngine;
        super.chatModel= chatModel;
        super.resourceLoader = resourceLoader;
        return this;
    }

    @Override
    public List<Map<String,Object>> executeSql(String sql)  {
        if (sql == null || sql.trim().isEmpty()) {
            throw new IllegalArgumentException("SQL cannot be null or empty");
        }
        try {
            log.info("Executing SQL: {}", sql);
            return executeService.executeSql(sql);
        } catch (Exception e) {
            log.error("Failed to execute SQL: {}", sql);
            throw new RuntimeException("Failed to execute SQL", e);
        }
    }
}
